<template>
  <div class="wrapper-add-edit">
    <el-form ref="refForm" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="绑定的前端路由">
        <el-col :span="8">
          <el-tree-select
            v-model="idRoute"
            :data="allRouteList"
            :props="{ value: 'id', label: 'title' }"
            :render-after-expand="false"
            :current-node-key="0"
            value-key="id"
            placeholder="选择要绑定的前端路由"
            check-strictly
          />
        </el-col>
        <el-col :span="16" :push="1">
          <span>有些权限不需要对应一条路由，比如删除操作，这些情况选择“根路由”</span>
        </el-col>
      </el-form-item>

      <el-form-item label="标签" prop="tag">
        <el-col :span="8">
          <el-input ref="refTag" v-model="formData.tag" maxlength="10" show-word-limit />
        </el-col>
        <el-col :span="16" :push="1">
          <span>权限的中文标签，例：“管理员”</span>
        </el-col>
      </el-form-item>

      <el-form-item label="中文名称" prop="label">
        <el-col :span="8">
          <el-input ref="refLabel" v-model="formData.label" maxlength="10" show-word-limit @blur="onCheckLabel()" />
        </el-col>
        <el-col :span="16" :push="1">
          <span>权限的中文名称，例：“管理员添加”</span>
        </el-col>
      </el-form-item>

      <el-form-item label="英文代码" prop="code">
        <el-col :span="8">
          <el-input ref="refCode" v-model="formData.code" maxlength="20" show-word-limit @blur="onCheckCode()" />
        </el-col>
        <el-col :span="16" :push="1">
          <span>权限的英文代码，不可重复，注意全小写，例：“admin_add”</span>
        </el-col>
      </el-form-item>

      <el-form-item>
        <el-button type="success" @click="onAdd()">确定添加</el-button>
        <el-button type="info" @click="onBack2List">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { AryToTree } from '@/utils/array'
import { toastSuccess, toastError } from '@/utils/toast'

import router from '@/router'
import store from '@/store'
import { defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
  name: 'PurviewAddView',
  setup() {
    const formData = ref({
      id: 0,
      label: '',
      code: '',
      serverUrl: '',
      httpMethod: '',
      bodyParams: '',
      tag: '',
    })
    const allRouteList = ref([])
    const idRoute = ref(1)
    const refForm = ref(null)
    const refTag = ref(null)
    const refLabel = ref(null)
    const refCode = ref(null)

    const rules = ref({
      tag: [{ required: true, message: '请输入关键字词', trigger: 'blur' }],
      label: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
      code: [{ required: true, message: '请输入权限代码', trigger: 'blur' }],
    })

    const listAll = () => {
      store
        .dispatch('sys_front_route/listAll')
        .then((response) => {
          allRouteList.value = AryToTree(response, 0)
        })
        .catch((error) => {
          console.log('从服务器API得到所有的路由数组出现错误：', error)
        })
    }
    // 提交表单
    const onAdd = async () => {
      if (await onCheckLabel()) {
        toastError('权限名称已使用！')
        return
      }
      if (await onCheckCode()) {
        toastError('权限代码已使用！')
        return
      }
      refForm.value.validate((valid) => {
        if (!valid) {
          toastError('表单验证失败！请检查您的输入！')
          return
        }
        // 执行到这里，说明表单验证通过
        store
          .dispatch('sys_purview/add', {
            SysPurview: formData.value,
            FrontRouteId: idRoute.value,
          })
          .then(() => {
            toastSuccess('添加权限成功！')
            router.push({ path: 'list-all' })
          })
          .catch((error) => {
            console.log('添加权限出现错误：', error)
          })
      })
    }
    const onBack2List = () => {
      router.push({ path: 'list-all' })
    }
    // 检查权限中文名称是否已使用
    const onCheckLabel = () => {
      const label = formData.value.label
      if (label === '') return true
      const paramsJson = {
        Id: 0,
        Label: label,
      }
      return store
        .dispatch('sys_purview/checkLabel', paramsJson)
        .then((response) => {
          return response.IsAdded
        })
        .catch((error) => {
          console.log('查询权限中文名称是否已添加时出现错误：', error)
          return true
        })
    }
    // 检查权限代码是否已使用
    const onCheckCode = () => {
      const code = formData.value.code
      if (code === '') return true
      const paramsJson = {
        Id: 0,
        Code: code,
      }
      return store
        .dispatch('sys_purview/checkCode', paramsJson)
        .then((response) => {
          return response.IsAdded
        })
        .catch((error) => {
          console.log('查询权限代码名称是否已添加时出现错误：', error)
        })
    }

    onMounted(() => {
      listAll()
    })

    return {
      formData,
      rules,
      allRouteList,
      idRoute,
      refForm,
      refTag,
      refLabel,
      refCode,
      listAll,
      onAdd,
      onBack2List,
      onCheckLabel,
      onCheckCode,
    }
  },
})
</script>

<style lang="scss" scoped></style>
